package com.hut.myblog.service.Impl;

import com.hut.myblog.bean.Comment;
import com.hut.myblog.dao.CommentMapper;
import com.hut.myblog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentServiceImpl implements CommentService {



    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {

        return commentMapper.findByBlogId(blogId);
    }

    @Override
    public Comment saveComment(Comment comment) {
        Long parentCommentId = comment.getParentComment().getId();
        if(parentCommentId != -1){//如果父id不为-1，表示有父节点。
            comment.setParentComment(commentMapper.findOne((parentCommentId)));
        }else {
            comment.setParentComment(null);
        }
        comment.setCreateTime(new Date());
        commentMapper.save(comment);
        return null;
    }
    @Override
    public  List<Comment> listChildrenComment(Long blogId) {//这个comment只设置博客id,父亲节点为null

        //拿到此篇博客的所有根节点
        List<Comment> rootComments = commentMapper.findByBlogId(blogId);
        List<Comment> comments = new ArrayList<>();
        //对根结点进行递归。
        for (Comment rootComment : rootComments) {

            System.out.println("========================"+rootComment.toString() + rootComment.getBlog() );
            replies = new ArrayList<>();//清空根评论replies
            recursively(rootComment);
            rootComment.setReplyComments(replies);
            comments.add(rootComment);
        }

        return comments;//根结点，根结点全部孩子
    }
    //根评论，根评论下的子评论（通过遍历出来）
    Map<Comment,List<Comment>> map = new LinkedHashMap();
    List<Comment> replies = new ArrayList<>();

    public void recursively(Comment comment){
        //判断这个节点是否还有孩子，有则继续递归，无就完成此方法
        if(commentMapper.listChildrenComment(comment).size() > 0){
            for (Comment childComment : commentMapper.listChildrenComment(comment)) {
                System.out.println("---------------------拿到"+childComment +"---------------------");
                childComment.setParentComment(comment);
                replies.add(childComment);
                recursively(childComment);
            }
        }
    }
}
